<template>
  <div>
    <!-- 仓库列表表格 -->
    <el-table :data="warehouses" border style="width: 100%">
      <el-table-column prop="id" label="仓库 ID" width="100"></el-table-column>
      <el-table-column prop="name" label="仓库名称" width="180">
        <template #default="scope">
          <el-link :underline="false" @click="getGoodsByWarehouse(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="仓库位置" width="200"></el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="decoration" label="描述"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" @click="getGoodsByWarehouse(scope.row)">查看库存</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 仓库库存抽屉 -->
    <el-drawer v-model="table" direction="rtl" size="50%">
      <div style="width: 100%; text-align: center; margin-bottom: 30px; margin-top: -20px">
        <span style="font-family: STXingkai; font-size: 25px; color: #38b2ac">{{ currentWarehouseName }}</span>
      </div>
      <el-table :data="stockData" style="width: 100%; height: 500px">
        <el-table-column fixed prop="id" label="货物 ID" width="100" align="center"></el-table-column>
        <el-table-column fixed prop="name" label="货物名称" width="150" align="center"></el-table-column>
        <el-table-column prop="weight" label="货物重量" width="120" align="center"></el-table-column>
        <el-table-column prop="volume" label="货物体积" width="120" align="center"></el-table-column>
        <el-table-column prop="quality" label="品质" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getQualityTagType(scope.row.quality)">
              {{ getQualityText(scope.row.quality) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="存货数量" width="120" align="center"></el-table-column>
        <el-table-column prop="wareHouseId" label="仓库 ID" width="100" align="center"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="划拨" width="100" align="center">
          <template #default="scope">
            <el-button type="primary" @click="showTransferWindow(scope.row)">划拨</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <!-- 划拨弹窗 -->
    <el-dialog v-model="dialogOverflowVisible" :title="currentGoods" width="500" draggable>
      <el-table :data="transferRows" style="width: 100%">
        <el-table-column label="目标仓库" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.targetWarehouse" placeholder="请选择目标仓库">
              <el-option
                  v-for="warehouse in filteredWarehouses"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="划拨数量" width="180">
          <template #default="scope">
            <el-input-number
                v-model="scope.row.num"
                :min="0"
                :max="getMaxNum(scope.$index)"
                @change="validateQuantity(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <div>
              <el-button
                  type="primary"
                  size="small"
                  :disabled="!scope.row.targetWarehouse || !scope.row.num || scope.row.num <= 0"
                  @click="addRow"
              >
                添加一行
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  :disabled="transferRows.length === 1"
                  @click="removeRow(scope.$index)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 15px; color: #606266;">
        剩余可划拨数量: {{ currentGoodsCount - totalTransferred }}
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogOverflowVisible = false">取消</el-button>
          <el-button type="primary" @click="transfer" :disabled="totalTransferred === 0">确认划拨</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watchEffect } from 'vue';
import axios from 'axios';
import { ElMessage } from "element-plus";

interface Warehouse {
  id: number;
  name: string;
  address: string;
  createTime: Date;
  decoration: string;
}

interface Goods {
  id: number;
  name: string;
  weight: number;
  volume: number;
  quality: number;
  count: number;
  wareHouseId: number;
  updateTime: Date;
}

interface TransferRow {
  targetWarehouse: number;
  num: number;
}

const warehouses = ref<Warehouse[]>([]);
const stockData = ref<Goods[]>([]);
const size = ref<'default' | 'large' | 'small'>('default');
const table = ref(false);
const currentWarehouseName = ref('');
const currentWarehouseId = ref(0);
const dialogOverflowVisible = ref(false);
const currentGoods = ref('');
const currentGoodsCount = ref(0);
const currentGoodsId = ref(0);
const transferRows = ref<TransferRow[]>([]);
const filteredWarehouses = ref<Warehouse[]>([]);

// 计算总划拨数量
const totalTransferred = computed(() => {
  return transferRows.value.reduce((sum, row) => sum + (row.num || 0), 0);
});

// 格式化日期方法
const formatDate = (timestamp: number | string | Date): string => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 货物品质标签样式
const getQualityTagType = (quality: number): string => {
  switch (quality) {
    case 0:
      return 'success';
    case 1:
      return 'warning';
    case 2:
      return 'danger';
    default:
      return '';
  }
};

// 货物品质显示文本
const getQualityText = (quality: number): string => {
  switch (quality) {
    case 0:
      return '优质';
    case 1:
      return '良品';
    case 2:
      return '次品';
    default:
      return '未知';
  }
};

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const res = await axios.get('http://localhost:8080/warehouse/findAll');
    warehouses.value = res.data.data;
  } catch (error) {
    console.error('获取仓库列表失败:', error);
  }
};

watchEffect(fetchWarehouses);

// 获取仓库货物信息
const getGoodsByWarehouse = async (row: Warehouse) => {
  currentWarehouseName.value = row.name;
  currentWarehouseId.value = row.id;
  table.value = true;
  try {
    const res = await axios.get(`http://localhost:8080/warehouse/findGoodsById`, {
      params: {
        id: currentWarehouseId.value,
      },
    });
    stockData.value = res.data.data;
  } catch (error) {
    console.error('获取仓库货物信息失败:', error);
    table.value = false;
  }
};

// 显示划拨弹窗
const showTransferWindow = (goods: Goods) => {
  dialogOverflowVisible.value = true;
  const qualityMap = {
    0: '优质',
    1: '一般',
    2: '较差',
  };
  currentGoods.value = `${goods.name}(${qualityMap[goods.quality]})`;
  currentGoodsCount.value = goods.count;
  currentGoodsId.value = goods.id;

  // 过滤掉当前仓库
  filteredWarehouses.value = warehouses.value.filter(
      (warehouse) => warehouse.id !== goods.wareHouseId
  );

  // 初始化划拨行 - 默认选择第一个仓库
  transferRows.value = [
    {
      targetWarehouse: filteredWarehouses.value[0]?.id || 0,
      num: 0,  // 划拨数量默认为0
    },
  ];
};

// 获取每行的最大可划拨数量
const getMaxNum = (index: number) => {
  return currentGoodsCount.value - totalTransferred.value + (transferRows.value[index].num || 0);
};

// 添加划拨行
const addRow = () => {
  // 默认选择第一个仓库
  transferRows.value.push({
    targetWarehouse: filteredWarehouses.value[0]?.id || 0,
    num: 0,  // 划拨数量默认为0
  });
};

// 删除划拨行
const removeRow = (index: number) => {
  if (transferRows.value.length > 1) {
    transferRows.value.splice(index, 1);
  } else {
    // 如果是最后一行，重置为0
    transferRows.value[0].num = 0;
  }
};

// 验证划拨数量
const validateQuantity = (row: TransferRow) => {
  // 确保数量不小于0
  if (row.num < 0) {
    row.num = 0;
  }

  // 计算最大允许值
  const maxAllowed = currentGoodsCount.value - totalTransferred.value + row.num;
  if (row.num > maxAllowed) {
    row.num = maxAllowed;
    ElMessage.warning(`划拨数量不能超过${maxAllowed}`);
  }
};

// 划拨货物
async function transfer() {
  // 验证是否有有效划拨
  if (totalTransferred.value <= 0) {
    ElMessage.warning("请设置划拨数量");
    return;
  }

  // 构造请求数据
  const requestData = {
    fromWarehouseId: currentWarehouseId.value,
    goodsId: currentGoodsId.value,
    transferRows: transferRows.value.map(row => ({
      targetWarehouse: row.targetWarehouse,
      num: row.num
    }))
  };

  try {
    const res = await axios.put(
        'http://localhost:8080/warehouse/transfer',
        requestData,
        { headers: { 'Content-Type': 'application/json' } }
    );

    ElMessage.success(res.data.msg);
    dialogOverflowVisible.value = false;
    // 刷新仓库数据
    await getGoodsByWarehouse({
      id: currentWarehouseId.value,
      name: currentWarehouseName.value,
    } as Warehouse);
  } catch (error) {
    console.error("划拨失败:", error);
    ElMessage.error("划拨失败: " + (error.response?.data?.msg || error.message));
  }
}
</script>

<style>

</style>